package com.beiding.workordersystem.orders.generalorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beiding.workordersystem.common.service.BaseService;
import com.beiding.workordersystem.common.standard.E;
import com.beiding.workordersystem.common.utils.TreeUtils;
import com.beiding.workordersystem.orders.generalorder.dao.GeneralOrderDao;
import com.beiding.workordersystem.orders.generalorder.dao.OrderTypeDao;
import com.beiding.workordersystem.orders.generalorder.entity.GeneralOrder;
import com.beiding.workordersystem.orders.generalorder.entity.OrderType;
import com.beiding.workordersystem.orders.generalorder.service.OrderTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderTypeServiceImpl extends BaseService implements OrderTypeService {

    @Autowired
    private OrderTypeDao orderTypeDao;

    @Autowired
    private GeneralOrderDao generalOrderDao;

    @Override
    public void save(OrderType type) {
        E.isTrue(orderTypeDao.exist(new QueryWrapper<OrderType>().lambda().eq(OrderType::getId, type.getPid())), "父节点不存在");
        if (fillId(type)) {
            E.isFalse(orderTypeDao.exist(new QueryWrapper<OrderType>().lambda().eq(OrderType::getPid, type.getPid()).eq(OrderType::getName, type.getName())), "不能在同一个父节点下增加同名的两个分类");

            orderTypeDao.insert(type);

        } else {
            orderTypeDao.updateById(type);
        }

    }

    @Override
    public void delete(String id) {
        E.isFalse("0".equals(id), "根节点禁止删除");
        E.isFalse(orderTypeDao.exist(new QueryWrapper<OrderType>().lambda().eq(OrderType::getPid, id)), "当前节点下存在子节点不能删除");
        E.isFalse(generalOrderDao.exist(new QueryWrapper<GeneralOrder>().lambda().eq(GeneralOrder::getTypeId, id)), "当前工单类型下存在关联的工单,无法删除");
        orderTypeDao.deleteById(id);
    }

    @Override
    public OrderType tree() {
        OrderType orderType = orderTypeDao.selectById("0");
        TreeUtils.fillChildren(orderType, "children", p -> orderTypeDao.selectList(new QueryWrapper<OrderType>().lambda().eq(OrderType::getPid, p.getId())),
                (p, o) -> {
                    if (!o.getId().equals("0")) {
                        if (o.getPid().equals("0")) {
                            o.setFullName(o.getName());
                        } else {
                            o.setFullName(p.getFullName() + "/" + o.getName());
                        }
                    }
                }
        );
        return orderType;
    }
}
